package pers.kevin.fsm.client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class TcpClient {
	
	public static void main(String[] args) {
	        BufferedWriter writer = null;
		Socket socket = null;
		BufferedReader reader = null;
		BufferedReader reader2 = null;
		try {
			socket = new Socket("localhost", 9000);
			//get console input.
			reader = new BufferedReader(new InputStreamReader(System.in));
			writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			reader2 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String readLine = null;
			while((readLine = reader.readLine()) != null){
			        //read a line from console and write a line to server.
				writer.write(readLine);
				writer.newLine();
				writer.flush();
				if(readLine.equals("quit")){
				    break;
				}
				String result = reader2.readLine();
				System.out.println(result);
			}
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if(reader != null) {
				    reader.close();
				}
				if(reader2 != null){
				    reader2.close();
				}
				if(socket != null) {
				    socket.close();
				}
				if(writer != null) {
				     writer.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
